package com.platform.module.common.exception;

import com.platform.module.common.base.CodeEnum;
import com.platform.module.common.base.CommonResp;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

/**
 * @author Long
 **/
@Slf4j
@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandle {

    @ExceptionHandler({Exception.class})
    @Order(999999)
    public CommonResp<?> handle(Exception exception) {
        if (exception instanceof CommonException e) {
            return CommonResp.fail(e.code(), e.msg());
        }
        if (exception instanceof IllegalArgumentException) {
            return CommonResp.fail("402", exception.getLocalizedMessage());
        } else if (exception instanceof IllegalAccessException) {
            return CommonResp.fail("500", exception.getLocalizedMessage());
        } else if (exception instanceof ServletRequestBindingException) {
            return CommonResp.fail("401", "Bad Request!");
        } else if (exception instanceof HttpMessageNotReadableException) {
            return CommonResp.fail("404", "Param Error!");
        } else if (exception instanceof HttpRequestMethodNotSupportedException) {
            return CommonResp.fail("900", "Method Not Allowed!");
        } else if (exception instanceof NoHandlerFoundException) {
            return CommonResp.fail("404", "Not Found!");
        } else if (exception instanceof NoResourceFoundException) {
            return CommonResp.fail("404", "Not Found!");
        } else if (exception instanceof MethodArgumentNotValidException) {
            log.error("接口参数错误", exception);
            return CommonResp.fail(CodeEnum.参数值错误);
        } else if (exception instanceof ConstraintViolationException) {
            log.error("参数值校验错误 {}", exception.getMessage());
            return CommonResp.fail(CodeEnum.参数值错误);
        }
        log.error("Internal Server Error!", exception);
        return CommonResp.fail("500", "Internal Server Error!");
    }

}
